package com.yicong.ants.manager;

import android.content.Context;
import android.util.SparseIntArray;
import android.webkit.CookieManager;
import android.webkit.WebStorage;

import com.cchao.simplelib.LibCore;
import com.cchao.simplelib.core.JsonHelper;
import com.cchao.simplelib.core.Logs;
import com.cchao.simplelib.core.PrefHelper;
import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.RxBus;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.ui.activity.BaseStatefulActivity;
import com.cchao.simplelib.util.CallBacks;
import com.cchao.simplelib.util.StringHelper;
import com.yicong.ants.Constants;
import com.yicong.ants.bean.account.RecFriendQrBean;
import com.yicong.ants.bean.account.UserBean;
import com.yicong.ants.bean.base.RespBean;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.ui.me.UserInfoActivity;
import com.yicong.ants.ui.me.account.LoginActivity;
import com.yicong.ants.utils.ConstantCodeUtils;
import com.yicong.ants.utils.InitUtil;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.disposables.Disposable;

/**
 * @author cchao
 * @version 2019-05-24.
 */
public class UserManager {

    private static UserBean mUserBean;
    private static SparseIntArray mNewsReadMap = new SparseIntArray();

    static {
        mUserBean = JsonHelper.toObject(PrefHelper.getString(Constants.Prefs.USER_INFO), UserBean.class);
    }

    public static boolean isLogin() {
        return mUserBean != null;
    }

    public static boolean notLogin() {
        return !isLogin();
    }

    public static boolean notBindCard() {
        return mUserBean == null || !mUserBean.isBindCard();
    }

    /**
     * 未登录 就跳转登录
     *
     * @param context
     * @return 已登录
     */
    public static boolean isLoginElseTurn(Context context) {
        if (notLogin()) {
            routeLoginResult(context, ConstantCodeUtils.START_LOGIN);
        }
        return isLogin();
    }

    /**
     * 未登录 就跳转登录
     *
     * @return 是未登录
     */
    public static boolean isNotLoginElseTurn(Context context) {
        return !isLoginElseTurn(context);
    }

    /**
     * 未实名 就跳转实名
     */
    public static boolean isNotAuthElseTurn(Context context) {
        if (isNotLoginElseTurn(context)) {
            return true;
        }

        if (!mUserBean.getIsAuth()) {
            Router.turnTo(context, UserInfoActivity.class).start();
            UiHelper.showToast("请先实名认证");
            return true;
        }
        return false;
    }

    public static void refreshUserInfo() {
        if (!isLogin()) {
            return;
        }

        Map<String, String> map = new HashMap<>(4);
        map.put("mobile", UserManager.getMobile());
        Disposable disposable = RetrofitHelper.getApis().refreshUserInfo(map)
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    if (respBean.isCodeFail()) {
                        UiHelper.showToast(respBean.getMsg());
                        return;
                    }
                    mUserBean = respBean.getData();
                    UserManager.updateUserBean(mUserBean);
                }, RxHelper.getErrorConsumer());
    }

    public static Disposable refreshDashboard(CallBacks.Str callBack) {
        return RetrofitHelper.getApis().refreshDashboard()
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    if (respBean.isCodeFail()) {
                        UiHelper.showToast(respBean.getMsg());
                        return;
                    }
                    if (isLogin()) {
                        UserManager.updateUserBean(respBean.getData().getUser_info());
                    }
                    callBack.onCallBack(respBean.getData().getTax_total());
                    BusinessHelper.mDashBoard = respBean.getData();
                }, throwable -> {
                    Logs.logException(throwable);
                    RxBus.get().postEvent(Constants.Event.Refresh_Dashboard_Fail);
                });
    }

    public static void logout() {
        if (notLogin()) {
            return;
        }
        PrefHelper.remove(Constants.Prefs.USER_INFO);
        CookieManager.getInstance().removeAllCookie();
        CookieManager.getInstance().removeSessionCookie();
        WebStorage.getInstance().deleteAllData();
        mUserBean = null;
        InitUtil.INSTANCE.initLiveSDK(LibCore.getContext());
        InitUtil.initTigerTally();
    }

    public static UserBean getUserBean() {
        return mUserBean;
    }

    public static boolean haveNiceNumber() {
        if (notLogin()) {
            return false;
        }
        return StringHelper.isNotEmpty(mUserBean.getNice_number());
    }

    public static void updateUserBean(UserBean userBean) {
        // 用户id 相同并且回传没有token （只获取用户信息）
        // 不清空 token，将老的token 赋值给新的用户实体
        if (mUserBean != null) {
            String token = mUserBean.getJwt_token();
            if (userBean.getId().equals(mUserBean.getId()) &&
                    StringHelper.isEmpty(userBean.getJwt_token())) {
                userBean.setJwt_token(token);
            }
        }
        mUserBean = userBean;
        PrefHelper.putString(Constants.Prefs.USER_INFO, JsonHelper.toJson(mUserBean));
        RxBus.get().postEvent(Constants.Event.Update_Me_Info);
        InitUtil.initTigerTally();
        InitUtil.INSTANCE.initLiveSDK(LibCore.getContext());
    }

    public static String getUserId() {
        if (UserManager.notLogin()) {
            return "";
        }
        return mUserBean.getId();
    }

    public static String getMobile() {
        if (UserManager.notLogin()) {
            return "";
        }
        return mUserBean.getMobile();
    }

    public static void havePayPwd(BaseStatefulActivity baseView, CallBacks.Int runnable) {
        baseView.addSubscribe(RetrofitHelper.getApis().havePayPwd(Collections.emptyMap())
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    baseView.hideProgress();
                    if (respBean.isCodeFail()) {
                        baseView.showToast(respBean.getMsg());
                        return;
                    }
                    if (runnable != null) {
                        runnable.onCallBack(respBean.getData().get("havePayPwd"));
                    }
                }, RxHelper.getHideProgressConsumer(baseView)));
    }

    public static void toggleCollect(boolean toggle, String scenicId, Runnable runnable) {
        Map<String, String> map = new HashMap<>();
        map.put("type", String.valueOf(toggle ? 1 : 2));
        map.put("scid", scenicId);
        Disposable disposable = RetrofitHelper.getApis().toggleCollect(map)
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    if (respBean.isCodeFail()) {
                        UiHelper.showToast(respBean.getMsg());
                        return;
                    }
                    runnable.run();
                }, RxHelper.getErrorConsumer());
    }

    public static void getScenicQrCode(CallBacks.Str callBacks) {
        Map<String, String> map = new HashMap<>(4);
        map.put("u_id", UserManager.getUserId());
        Disposable disposable = RetrofitHelper.getApis().getUserQrCode(map)
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    if (respBean.isCodeFail()) {
                        UiHelper.showLongToast(respBean.getMsg());
                        return;
                    }
                    callBacks.onCallBack(respBean.getData());
                }, RxHelper.getErrorConsumer());
    }

    public static void getRecFriendQr(CallBacks.Object<RecFriendQrBean> callBacks) {
        Map<String, String> map = new HashMap<>(4);
        map.put("uid", UserManager.getUserId());
        Disposable disposable = RetrofitHelper.getApis().getRecFriendQr(map)
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    if (respBean.isCodeFail()) {
                        UiHelper.showToast(respBean.getMsg());
                        return;
                    }
                    callBacks.onCallBack(respBean.getData());
                }, RxHelper.getErrorConsumer());
    }

    public static void putReadRecord(int newsId, int location) {
        mNewsReadMap.put(newsId, location);
    }

    public static int getReadRecord(int newsId) {
        return mNewsReadMap.get(newsId);
    }

    public static void routeLogin(Context context) {
        Router.turnTo(context, LoginActivity.class).start();
    }

    public static void checkAuthRouter(Context context, RespBean respBean) {
        if (respBean.getCode().equals(Constants.Resp_Code.No_Auth)) {
            Router.turnTo(context, UserInfoActivity.class).start();
        }
    }

    public static void routeLoginResult(Context context, int result) {
        Router.turnTo(context, LoginActivity.class).startForResult(result);
    }
}
